<?php

declare(strict_types=1);

namespace App\Job;

use App\Model\Distributors;
use App\Model\Normal;
use App\Model\Order;
use App\Services\PushService;
use Hyperf\AsyncQueue\Job;

class PushOrder extends Job
{
    public $orderId;
    public $type;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;


    public function __construct($orderId,$type = 'start')
    {
        // 这里最好是普通数据，不要使用携带 IO 的对象，比如 PDO 对象
        $this->orderId = $orderId;
        $this->type = $type;

    }

    public function handle()
    {
        $order = Order::where('id',$this->orderId)->with('charge')->first();
        $distributor = Distributors::find($order->distributor_id);
        if($this->type == 'end'){
            $data['amount'] = $order->power_fee-$order->return_fee;
            $data['electricAmount'] = $order->use_fee;
            $data['electricQuantity'] = round($order->use_elec>0?$order->use_elec/1000:0,2);
            $data['finishTime'] = $order->stop_at;
            $data['serviceAmount'] = $order->charge_service;
            $data['status'] = 2;
        }else{
            $data['status'] = 1;
        }
        $data['siteCode'] = $order->station_id;
        $data['createTime'] = $order->created_at;
        $data['deviceCode'] = $order->device_id;
        $data['devicePortNumber'] = $order->channel_number;
        $data['orderNo'] = $order->number;
        $templeteJson['name'] = $order->charge->name;
        $templeteJson['type'] = 2;
        $templeteJson['isBack'] = 1;
        $templeteJson['detail']['id'] = $order->id;
        $templeteJson['detail']['num'] = 0;
        $templeteJson['detail']['cost'] = $order->charge->pre_fee;
        $templeteJson['detail']['unit'] = 0;
        $templeteJson['detail']['serviceFee'] = 0;
        $templeteJson['detail']['chargeTemplateId'] = $order->charge->id;
        $templeteJson['detail']['createTime'] = $order->charge->created_at;
        $templeteJson['detail']['deleteFlag'] = 0;
        $templeteJson['detail']['operatorId'] = $order->distributor_id;
        $templeteJson['detail']['updateTime'] =  $order->charge->updated_at;
        $templeteJson['detail']['hasBeenUsed'] = 1;
        $templeteJson['detail']['operatorName'] = $distributor->name;
        $data['templateJson'] = json_encode($templeteJson);
        $pushService = new PushService();
        $result = $pushService->sendOrder($data);
        Normal::logger('push-order-----'.json_encode($result),'order-queue');
    }
}
